<script setup>
import CmpEdit from '@/views/liteflow/cmp/CmpEdit1.vue'
import axios from '@axios'
import { reactive, ref } from 'vue'
import { VDataTableServer } from 'vuetify/labs/VDataTable'

// 组件统计
const cmpListMeta = [
  {
    icon: 'tabler-user-plus',
    color: 'error',
    title: '全部组件',
    stats: '0',
    percentage: +0,
  },
  {
    icon: 'tabler-user-check',
    color: 'success',
    title: '动态组件',
    stats: '0',
    percentage: -0,
  },
  {
    icon: 'tabler-user-exclamation',
    color: 'warning',
    title: '脚本组件',
    stats: '0',
    percentage: +0,
  },
  {
    icon: 'tabler-user',
    color: 'primary',
    title: '其他组件',
    stats: '0',
    percentage: +0,
  },
]

// 组件分类
const open = ref([
  'Users',
  'Admin',
])

const admins = [
  [ 'Management', 'tabler-users' ],
  [ 'Settings' ],
]

const cruds = [
  [ 'Create', 'tabler-plus' ],
  [ 'Read', 'tabler-file' ],
  [ 'Update', 'tabler-reload' ],
  [ 'Delete', 'tabler-trash' ],
]

// 组件列表

//查询条件
const componentId = ref()
const componentName = ref()
const type = ref()

// 组件类型-下拉选择框
const nodeTypeList = reactive([])

const nodeTypeSelect = () => {
  axios.post('/liteflow/cmp/type/options', { }).then(r => {
    nodeTypeList.push(...r.data.data)
  }).catch(e => {
    console.error(e)
  })
}

// 表头
const headers = [
  {
    title: '组件ID',
    key: 'componentId',
  },
  {
    title: '组件名称',
    key: 'componentName',
  },
  {
    title: '组件类型',
    key: 'type',
  },
  {
    title: 'Java类',
    key: 'clazz',
  },
  {
    title: 'EL表达式',
    key: 'el',
  },
  {
    title: '操作',
    key: 'actions',
    sortable: false,
  },
]

// 分页参数
const options = ref({
  page: 1,
  itemsPerPage: 10,
  sortBy: [],
  groupBy: [],
  search: undefined,
})

// 分页查询
const totalPage = ref(1) //总页数
const totalRows = ref(0) //总记录数
const list = ref([]) // 当前分页数据

const fetchList = () => {
  axios.post('/liteflow/cmp/page', {
    type: type.value,
    componentName: componentName.value,
    componentId: componentId.value,
    options: options.value,
  }).then(r => {
    let response = r.data.data
    list.value = response.list
    totalPage.value = response.totalPage
    totalRows.value = response.totalRow
    options.value.page = response.page
  }).catch(e => {
    console.error(e)
  })
}

watchEffect(fetchList)

// 删除操作
const deleteId = ref('')
const deleteVisible = ref(false)

const deleteOper = id => {
  deleteVisible.value = true
  deleteId.value = id
}

const deleteAgreeOper = id => {
  axios.post('/liteflow/cmp/delete', { 
    componentId: deleteId.value,
  }).then(r => {
    fetchList()
    deleteVisible.value = false
    deleteId.value = ''
  }).catch(e => {
    console.error(e)
  })
}

// 新增操作
// const isCmpVisible = ref(false)

// const addNewCmp = cmpData => {
//   axios.post('/liteflow/cmp/add', cmpData).then(r => {
//     showMsg(r)
//     fetchList()
//   }).catch(e => {
//     console.error(e)
//   })
// }


// const editKey = ref(1)
// const isCmpEditVisible = ref(false)
// const editData = ref({})

// const updateCmp = cmp => {
//   editKey.value ++
//   isCmpEditVisible.value = true
//   editData.value = cmp
// }

// const updateCurrCmp = cmpData2 => {
//   axios.post('/liteflow/cmp/update', cmpData2).then(r => {
//     if(200 == r.data.code){
//       addVisible.value = true
//       addMsg.value = r.data.message
//       addMsgColor.value = 'success'
//     }else{
//       addVisible.value = true
//       addMsg.value = r.data.message
//       addMsgColor.value = 'error'
//     }
//     fetchList()
//   }).catch(e => {
//     console.error(e)
//   })
// }

// 新增&编辑操作
const editKey = ref(0)
const addUrl = ref('/liteflow/cmp/add')
const updateUrl = ref('/liteflow/cmp/update')
const currRow = ref({})
	
const addOper = () => {
  currRow.value = {}
  editVisible.value = true
  editKey.value++
}

const updateOper = row => {
  currRow.value = row
  editVisible.value = true
  editKey.value++
}

const editVisible = ref(false)
const editRef = ref(null)

const editCallMethod = () => {
  editVisible.value = false
  editRef.value.onSubmit()
}

const editCancelMethod = () =>{
  editVisible.value = false
}

const refreshPage = res => {
  showMsg(res)
  fetchList()
}

// 执行EL表达式
const execVisible = ref(false)
const execResult = ref('')
const execStatus = ref(200)

const execCmp = cmp => {
  axios.post('/liteflow/cmp/exec', {
    id: cmp.id,
  }).then(r => {
    execVisible.value = true
    if(200 == r.data.code){
      execStatus.value = 200
      execResult.value = r.data.data
    }else{
      execStatus.value = 500
      execResult.value = r.data.message
    }
  }).catch(e => {
    console.error(e)
  })
}

// 回调信息
const msgVisible = ref(false)
const msgContent = ref('')
const msgColor = ref('error')

const showMsg = res => {
  if(res){
    if(res.code == 200){
      msgVisible.value = true
      msgColor.value = "success"
      msgContent.value = res.message
    }else{
      msgVisible.value = true
      msgColor.value = "error"
      msgContent.value = res.message
    }
  }
}

// 初始化
onMounted(() => {
  nodeTypeSelect()
})
</script>

<template>
  <section>
    <VSnackbar
      v-model="msgVisible"
      location="top"
      :color="msgColor"
    >
      {{ msgContent }}
    </VSnackbar>
    <VRow>
      <VCol
        v-for="meta in cmpListMeta"
        :key="meta.title"
        cols="10"
        sm="6"
        lg="3"
      >
        <VCard>
          <VCardText class="d-flex justify-space-between">
            <div>
              <span>{{ meta.title }}</span>
              <div class="d-flex align-center gap-2 my-1">
                <h6 class="text-h4">
                  {{ meta.stats }}
                </h6>
                <span :class="meta.percentage > 0 ? 'text-success' : 'text-error'">( {{ meta.percentage > 0 ? '+' : '' }}{{ meta.percentage }})</span>
              </div>
            </div>

            <VAvatar
              rounded
              variant="tonal"
              :color="meta.color"
              :icon="meta.icon"
            />
          </VCardText>
        </VCard>
      </VCol>

      <!--
        <VSnackbar
        v-model="addVisible"
        location="top"
        :color="addMsgColor"
        >
        {{ addMsg }}
        </VSnackbar> 
      -->

      <VCol cols="3">
        <VList v-model:opened="open">
          <VListItem
            prepend-icon="tabler-home"
            title="Home"
            value="Home"
          />

          <VListGroup value="Users">
            <template #activator="{ props }">
              <VListItem
                v-bind="props"
                prepend-icon="tabler-users"
                title="Users"
              />
            </template>

            <VListGroup value="Admin">
              <template #activator="{ props }">
                <VListItem
                  v-bind="props"
                  title="Admin"
                />
              </template>

              <VListItem
                v-for="([title, icon], i) in admins"
                :key="i"
                :value="title"
                :title="title"
                :prepend-icon="icon"
              />
            </VListGroup>

            <VListGroup value="Actions">
              <template #activator="{ props }">
                <VListItem
                  v-bind="props"
                  title="Actions"
                />
              </template>

              <VListItem
                v-for="([title, icon], i) in cruds"
                :key="i"
                :value="title"
                :title="title"
                :prepend-icon="icon"
              />
            </VListGroup>
          </VListGroup>
        </VList>
      </VCol>

      <VCol cols="9">
        <VCard title="检索组件">
          <!-- 👉 Filters -->
          <VCardText>
            <VRow>
              <!-- 👉 Select Role -->
              <VCol
                cols="12"
                sm="4"
              >
                <VTextField
                  v-model="componentId"
                  label="组件ID"
                  clearable
                />
              </VCol>
              <!-- 👉 Select Plan -->
              <VCol
                cols="12"
                sm="4"
              >
                <VTextField
                  v-model="componentName"
                  label="组件名称"
                  clearable
                />
              </VCol>
              <VCol
                cols="12"
                sm="4"
              >
                <VSelect
                  v-model="type"
                  label="组件类型"
                  :items="nodeTypeList"
                  clearable
                  clear-icon="tabler-x"
                />
              </VCol>
            </VRow>
          </VCardText>

          <VDivider />

          <VCardText class="d-flex flex-wrap py-4 gap-4">
            <div class="me-3 d-flex gap-3">
              <AppSelect
                :model-value="options.itemsPerPage"
                :items="[
                  { value: 10, title: '10' },
                  { value: 20, title: '20' },
                  { value: 50, title: '50' },
                  { value: 100, title: '100' },
                ]"
                style="width: 6.25rem;"
                @update:model-value="options.itemsPerPage = parseInt($event, 10)"
              />
            </div>
            <VSpacer />

            <div class="d-flex align-center flex-wrap gap-4">
              <VBtn
                prepend-icon="tabler-plus"
                @click="addOper"
              >
                新增组件
              </VBtn>
            </div>
          </VCardText>

          <VDivider />

          <!-- SECTION datatable -->
          <VDataTableServer
            v-model:items-per-page="options.itemsPerPage"
            v-model:page="options.page"
            :items="list"
            :items-length="totalRows"
            :headers="headers"
            class="text-no-wrap"
            @update:options="options = $event"
          >
            <!-- Plan -->
            <template #item.componentId="{ item }">
              <span class="font-weight-medium">{{ item.raw.componentId }}</span>
            </template>

            <template #item.componentName="{ item }">
              <span class="font-weight-medium">{{ item.raw.componentName }}</span>
            </template>

            <template #item.type="{ item }">
              <span class="font-weight-medium"><VChip
                label
                color="success"
                size="small"
              >  {{ item.raw.type }} </VChip></span>
            </template>

            <template #item.clazz="{ item }">
              <span class="font-weight-medium">{{ item.raw.clazz }}</span>
            </template>

            <template #item.el="{ item }">
              <VBtn
                variant="plain"
                size="small"
                style="padding-left: 0;"
              >
                查看EL表达式
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  {{ item.raw.el }}
                </VTooltip>
              </VBtn>
            </template>

            <!-- Actions -->
            <template #item.actions="{ item }">
              <IconBtn @click="deleteOper(item.raw.componentId)">
                <VIcon icon="tabler-trash" />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  删除
                </VTooltip>
              </IconBtn>

              <IconBtn @click="updateOper(item.raw)">
                <VIcon icon="tabler-edit" />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  编辑
                </VTooltip>
              </IconBtn>

              <IconBtn @click="execCmp(item.raw)">
                <VIcon icon="tabler-player-play-filled" />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  调试
                </VTooltip>
              </IconBtn>
            </template>

            <!-- pagination -->
            <template #bottom>
              <VDivider />
              <div class="d-flex align-center justify-sm-space-between justify-center flex-wrap gap-3 pa-5 pt-3">
                <p class="text-sm text-disabled mb-0">
                  共<span style="color: #7367f0;">{{ totalRows }}</span>条记录
                </p>
                <VPagination
                  v-model="options.page"
                  :length="Math.ceil(totalRows / options.itemsPerPage)"
                  :total-visible="$vuetify.display.xs ? 1 : Math.ceil(totalRows / options.itemsPerPage)"
                >
                  <template #prev="slotProps">
                    <VBtn
                      variant="tonal"
                      color="default"
                      v-bind="slotProps"
                      :icon="false"
                    >
                      上一页
                    </VBtn>
                  </template>

                  <template #next="slotProps">
                    <VBtn
                      variant="tonal"
                      color="default"
                      v-bind="slotProps"
                      :icon="false"
                    >
                      下一页
                    </VBtn>
                  </template>
                </VPagination>
              </div>
            </template>
          </VDataTableServer>
          <!-- SECTION -->
        </VCard>

        <!-- 👉 新增组件 -->
        <!--
          <CmpAdd
          v-model:isDrawerOpen="isCmpVisible"
          @cmp-data="addNewCmp"
          /> 
        -->

        <!-- 编辑组件 -->
        <!--
          <CmpEdit
          :key="'cmp-edit-'+editKey"
          v-model:isDrawerOpen2="isCmpEditVisible"
          :edit-data="editData"
          @cmp-data2="updateCurrCmp"
          /> 
        -->

        <VDialog
          v-model="editVisible"
          fullscreen
          :scrim="false"
          transition="dialog-bottom-transition"
        >
          <VCard>
            <div>
              <VToolbar color="primary">
                <VBtn
                  icon
                  variant="plain"
                  @click="editVisible = false"
                >
                  <VIcon
                    color="white"
                    icon="tabler-x"
                  />
                </VBtn>

                <VToolbarTitle>设置</VToolbarTitle>

                <VSpacer />

                <VToolbarItems>
                  <VBtn
                    variant="text"
                    @click="editCancelMethod"
                  >
                    取消
                  </VBtn>
                  <VBtn
                    variant="text"
                    @click="editCallMethod"
                  >
                    保存
                  </VBtn>
                </VToolbarItems>
              </VToolbar>
            </div>
            <div style="height: 100%;padding: 24px;overflow-y: scroll;">
              <CmpEdit
                :key="editKey"
                ref="editRef"
                :curr-row="currRow"
                :add-url="addUrl"
                :update-url="updateUrl"
                @refreshPage="refreshPage"
              />
            </div>
          </VCard>
        </VDialog>

        <!-- 删除确认 -->
        <VDialog
          v-model="deleteVisible"
          width="300"
        >
          <DialogCloseBtn @click="deleteVisible = !deleteVisible" />
          <VCard title="提示">
            <VCardText> 是否删除组件[{{ deleteId }}]？ </VCardText>
            <VCardText class="d-flex justify-end gap-3 flex-wrap">
              <VBtn
                color="secondary"
                variant="tonal"
                @click="deleteVisible = false"
              >
                取消
              </VBtn>
              <VBtn @click="deleteAgreeOper">
                确定
              </VBtn>
            </VCardText>
          </VCard>
        </VDialog>

        <VSnackbar
          v-model="execVisible"
          multi-line
        >
          <span v-if="execStatus == 200">执行成功：</span>
          <span v-if="execStatus != 200">执行失败：</span>
          <br>
          {{ execResult }}
          <template #actions>
            <VBtn
              color="error"
              @click="execVisible = false"
            >
              关闭
            </VBtn>
          </template>
        </VSnackbar>
      </vcol>
    </vrow>
  </section>
</template>

<style lang="scss">
.text-capitalize {
  text-transform: capitalize;
}

.user-list-name:not(:hover) {
  color: rgba(var(--v-theme-on-background), var(--v-medium-emphasis-opacity));
}
</style>
